package dk.modified.radioonlineapp;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class RadioService extends Service implements
		MediaPlayer.OnErrorListener {

	private Looper mServiceLooper;
	private ServiceHandler mServiceHandler;
	private CommentsDataSource datasource;
	private static final String DEBUG_TAG = "RadioService";
	public  MediaPlayer mp = new MediaPlayer();
	public  String url;
	private int id;
	private static final int NOTIFICATION_ID = 1337;
	private int codeVersion;
	//private Handler mHandler = new Handler();

	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			try {

				preparePlayer();
				mp.setOnPreparedListener(new OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						mp.start();
						MainActivity.imgLoading.setVisibility(View.INVISIBLE);
						MainActivity.anim.stop();
						MainActivity.textBoxStat
						.setText(getString(R.string.textBoxStatPlay));				
						
					}
				});
			} catch (Exception e) {
			}
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		PackageInfo pInfo = null;
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		codeVersion = pInfo.versionCode;
		
		mp.setOnErrorListener(this);

		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		if (mgr != null) {
			mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		}
		datasource = new CommentsDataSource(this.getApplicationContext());
		
		datasource.Open();
		id = datasource.GetActiveID();
		try {
			if (MainActivity.searchGlobal
					&& MainActivity.tabHost.getCurrentTab() == 3) {
				url = MainActivity.url;
			} else {
				url = datasource.GetActiveURL().trim();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		datasource.Close();

		HandlerThread thread = new HandlerThread("ServiceStartArguments",
				Process.THREAD_PRIORITY_BACKGROUND);
		thread.start();
		// Get the HandlerThread's Looper and use it for our Handler
		mServiceLooper = thread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);
		
		//mp.setOnCompletionListener(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		if (mgr != null) {
			mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
		}
		datasource.Open();
		datasource.Close();
		releaseMediaPlayer();
		mServiceLooper.quit();
		removeNotification();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			
			if(url.length() < 1){
				
				MainActivity.play.setVisibility(View.VISIBLE);
				MainActivity.stop.setVisibility(View.GONE);
				MainActivity.textBoxStat.setText(getString(R.string.textBoxStatStop));
				MainActivity.imgLoading.setVisibility(View.GONE);
				//PostERROR
				ByteConverter.postData(String.valueOf(codeVersion),id,false);
				Toast.makeText(getApplicationContext(),
						getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
				this.stopSelf();		
				
			} 
			
			/*if (mp!=null) {
				// Updating progress bar
				updateProgressBar();
			}*/
			
			Message msg = mServiceHandler.obtainMessage();
			msg.arg1 = startId;
			mServiceHandler.sendMessage(msg);
			startForeground(NOTIFICATION_ID, addNotification());
			return START_STICKY;

		} catch (Exception e) {
			Log.e(DEBUG_TAG, "Player failed", e);
		}
		return Service.START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void releaseMediaPlayer() {
		if (mp != null) {
			if (mp.isPlaying()) {
				mp.stop();
			}
			mp.reset();
			mp.release();
			mp = null;
		}
	}

	private void preparePlayer() {
		if (mp == null) {
			mp = new MediaPlayer();
		}
		mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
		
		try {
			mp.setDataSource(url);
			mp.prepareAsync();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Notification addNotification() {
		Notification note;
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				this).setSmallIcon(R.raw.icon_notification)
				.setTicker(getString(R.string.textNotificationPlaying))
				.setContentTitle(getString(R.string.app_name))
				.setContentText(getString(R.string.textNotificationClick));

		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(contentIntent);
		note = builder.build();
		// Add as notification
		NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		manager.notify(NOTIFICATION_ID, note);

		return note;
	}

	// Remove notification
	private void removeNotification() {
		NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		manager.cancel(NOTIFICATION_ID);
	}

	PhoneStateListener phoneStateListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			//Bug fix: mp is sometime empty
			if (mp != null) {
				if (state == TelephonyManager.CALL_STATE_RINGING) {
					mp.setVolume(0, 0);
					// Incoming call: Pause music
				} else if (state == TelephonyManager.CALL_STATE_IDLE) {
					mp.setVolume(1, 1);
					// Not in call: Play music
				} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
					mp.setVolume(0, 0);
					// A call is dialing, active or on hold
				}
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	};

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		
		if (Build.VERSION.SDK_INT >= 16 && what==MediaPlayer.MEDIA_ERROR_UNKNOWN) {
			
			MainActivity.imgLoading.setVisibility(View.INVISIBLE);
			MainActivity.anim.stop();
			MainActivity.textBoxStat
			.setText(getString(R.string.textBoxStatPlay));
			Toast.makeText(getApplicationContext(),getString(R.string.known_issue), Toast.LENGTH_LONG).show();
		      return true;
		    }
		
		MainActivity.play.setVisibility(View.VISIBLE);
		MainActivity.stop.setVisibility(View.GONE);
		MainActivity.textBoxStat.setText(getString(R.string.textBoxStatStop));
		MainActivity.imgLoading.setVisibility(View.GONE);

		//PostERROR
		ByteConverter.postData(String.valueOf(codeVersion),id,false);
		
		Toast.makeText(getApplicationContext(),
				getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
		this.stopSelf();
		// TODO Auto-generated method stub
		return false;
	}

	
	/**
     * Update timer on seekbar
     * */
   /* public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    } */
    
    /**
     * Background Runnable thread
     * */
   /* private Runnable mUpdateTimeTask = new Runnable() {
           public void run() {
        	   if (mp!=null) {
               //long totalDuration = mp.getDuration();
               long currentDuration = mp.getCurrentPosition();
 
               // Displaying Total Duration time
               //MainActivity.songTotalDurationLabel.setText(""+Util.milliSecondsToTimer(totalDuration));

               // Displaying time completed playing
               MainActivity.songCurrentDurationLabel.setText(""+Util.milliSecondsToTimer(currentDuration));
 
               // Updating progress bar
               int progress = (int)(Util.getProgressPercentage(currentDuration, 600000));
               //Log.d("Progress", ""+progress);
               MainActivity.songProgressBar.setProgress(progress); 
               
               // Running this thread after 100 milliseconds
               mHandler.postDelayed(this, 100);
        	   }
           }
        };*/
}
